import json
import traceback

class DotContainer(dict):
	def __init__(self, *args, **kwargs):
		dict.__init__(self, *args, **kwargs)
		self.__dict__ = self

	def toDotContainer(data):
		if isinstance(data, dict):
			for k, v in data.items():
				if isinstance(v, dict):
					data[k] = DotContainer(v)
					DotContainer.toDotContainer(data[k])
		elif isinstance(data, list) or isinstance(data, tuple):
			for v in data:
				if isinstance(v, dict):
					v = DotContainer(v)
					DotContainer.toDotContainer(v)
		else:
			return data
		return DotContainer(data)

	def __getattr__(self, name):
		self.__dict__[name] = DotContainer()
		return self.__dict__[name]

class Document:
	def __init__(self, filename=None):
		self.__dict__['filename'] = filename

		if not filename:
			self.__dict__['root'] = DotContainer()
			return

		if not filename.endswith('.json'):
			filename += '.json'

		try:
			with open(filename, 'r', encoding='utf-8') as f:
				self.__dict__['root'] = DotContainer.toDotContainer(json.loads(f.read()))
		except FileNotFoundError:
			print('糖糖喵的小本本找不到了呢……', flush=True)
			print(f'是这本书呢：{filename}', flush=True)
			self.__dict__['root'] = DotContainer()

	def store(self):
		if not self.__dict__['filename']:
			return

		try:
			with open(self.__dict__['filename'], 'w', encoding='utf-8') as f:
				f.write(json.dumps(self.root, ensure_ascii=False,
								   sort_keys=True, indent=4, separators=(',', ': ')))
		except Exception:
			pass

	def __getattr__(self, name):
		return getattr(self.root, name)

	def __setattr__(self, key, val):
		setattr(self.root, key, val)